// 游戏状态管理
const game = {
  snake: [{x: 15, y: 15}],  // 蛇的初始位置
  aiSnake: [{x: 25, y: 15}], // AI蛇的初始位置
  food: {x: 5, y: 5, type: 'normal'},  // 食物的初始位置和类型
  direction: 'right',       // 初始方向
  aiDirection: 'left', // AI蛇的方向
  gridSize: 20,            // 网格大小
  speed: 200,              // 初始速度（毫秒）
  score: 0,                // 当前分数
  aiScore: 0, // AI的分数
  highScore: 0,            // 最高分
  isRunning: false,        // 游戏运行状态
  isPaused: false,         // 游戏暂停状态
  startTime: 0,            // 游戏开始时间
  gameTime: 0,             // 游戏运行时间
  obstacleMode: false,     // 障碍模式状态
  obstacles: [],           // 障碍物数组
  difficulty: 'medium',    // 游戏难度
  aiMode: false, // AI对战模式
  effects: {               // 特殊效果状态
      speedBoost: false,   // 速度提升
      speedBoostEndTime: 0,// 速度提升结束时间
      doubleScore: false,  // 双倍分数
      doubleScoreEndTime: 0,// 双倍分数结束时间
      shield: false,       // 护盾
      shieldEndTime: 0     // 护盾结束时间
  }
};

// 难度设置
const DIFFICULTY_SETTINGS = {
  easy: {
      obstacleCount: {min: 3, max: 5},
      foodProbability: {normal: 0.8, speedBoost: 0.07, doubleScore: 0.07, shield: 0.06},
      scoreMultiplier: 1
  },
  medium: {
      obstacleCount: {min: 5, max: 8},
      foodProbability: {normal: 0.7, speedBoost: 0.1, doubleScore: 0.1, shield: 0.1},
      scoreMultiplier: 1.5
  },
  hard: {
      obstacleCount: {min: 8, max: 12},
      foodProbability: {normal: 0.6, speedBoost: 0.15, doubleScore: 0.15, shield: 0.1},
      scoreMultiplier: 2
  }
};

// 食物类型定义
const FOOD_TYPES = {
  normal: {
      color: '#4CAF50',
      score: 10,
      probability: 0.7,
      effect: null
  },
  speedBoost: {
      color: '#FFC107',
      score: 15,
      probability: 0.1,
      effect: 'speedBoost',
      duration: 5000 // 5秒
  },
  doubleScore: {
      color: '#9C27B0',
      score: 20,
      probability: 0.1,
      effect: 'doubleScore',
      duration: 8000 // 8秒
  },
  shield: {
      color: '#2196F3',
      score: 25,
      probability: 0.1,
      effect: 'shield',
      duration: 10000 // 10秒
  }
};

// 获取画布上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// 页面加载完成时初始化游戏
window.addEventListener('load', function() {
  // 设置画布大小
  resizeCanvas();
  
  // 窗口大小改变时重设画布
  window.addEventListener('resize', resizeCanvas);
  
  // 从本地存储获取最高分
  const storedHighScore = localStorage.getItem('snakeHighScore');
  if (storedHighScore) {
    game.highScore = parseInt(storedHighScore);
  }
  
  // 初始化游戏
  initGame();
  
  // 绑定游戏控制按钮事件
  document.getElementById('startBtn').addEventListener('click', startGame);
  document.getElementById('pauseBtn').addEventListener('click', togglePause);
  document.getElementById('restartBtn').addEventListener('click', restartGame);
  document.getElementById('obstacleModeBtn').addEventListener('click', toggleObstacleMode);
  document.getElementById('aiModeBtn').addEventListener('click', toggleAIMode);
  
  // 速度控制
  const speedControl = document.getElementById('speedControl');
  speedControl.addEventListener('input', function() {
    const speed = parseInt(speedControl.value);
    game.speed = 300 - (speed * 25); // 将1-10的值转换为275-50毫秒
    document.getElementById('speedValue').textContent = speed;
  });
  
  // 难度选择
  document.getElementById('difficultySelect').addEventListener('change', function() {
    game.difficulty = this.value;
    if (game.obstacleMode) {
      // 如果当前是障碍模式，重新生成障碍物以应用新难度
      generateObstacles();
    }
  });
  
  // 初始化移动端控制
  initMobileControls();
  
  // 初始化游戏说明弹窗
  initInstructionsModal();
  
  // 绘制初始状态
  draw();
});

// 调整画布大小以适应屏幕
function resizeCanvas() {
  const container = document.querySelector('.game-container');
  const containerWidth = container.clientWidth;
  
  // 设置画布宽度与容器相同
  canvas.width = containerWidth;
  
  // 根据屏幕大小调整网格大小
  if (window.innerWidth < 360) {
    game.gridSize = 15; // 小屏幕使用更小的网格
  } else {
    game.gridSize = 20; // 普通屏幕使用标准网格
  }
  
  // 让画布保持正方形
  canvas.height = containerWidth;
  
  // 重新绘制
  if (game.isRunning) {
    draw();
  }
}

// 初始化游戏
function initGame() {
  // 计算中心位置
  const centerX = Math.floor(canvas.width / (2 * game.gridSize));
  const centerY = Math.floor(canvas.height / (2 * game.gridSize));

  // 重置游戏状态
  game.snake = [
    {x: centerX, y: centerY},
    {x: centerX - 1, y: centerY},
    {x: centerX - 2, y: centerY}
  ];
  game.aiSnake = [
    {x: centerX + 5, y: centerY},
    {x: centerX + 4, y: centerY},
    {x: centerX + 3, y: centerY}
  ];
  game.direction = 'right';
  game.aiDirection = 'left';
  game.score = 0;
  game.aiScore = 0;
  game.isRunning = false;
  game.isPaused = false;
  game.startTime = 0;
  game.gameTime = 0;
  game.obstacles = [];
  
  // 重置特殊效果
  game.effects = {
    speedBoost: false,
    speedBoostEndTime: 0,
    doubleScore: false,
    doubleScoreEndTime: 0,
    shield: false,
    shieldEndTime: 0
  };
  
  // 生成第一个食物
  generateFood();
  
  // 如果障碍模式开启，生成障碍物
  if (game.obstacleMode) {
    generateObstacles();
  }
  
  // 隐藏AI相关显示
  hideAIStats();
  
  // 更新显示
  updateDisplay();
  
  // 重置按钮状态
  document.getElementById('startBtn').style.display = 'block';
  document.getElementById('pauseBtn').style.display = 'none';
  document.getElementById('pauseBtn').textContent = '暂停';
  
  // 绘制初始状态
  draw();
}

// 隐藏AI相关显示
function hideAIStats() {
  document.querySelectorAll('.ai-stats').forEach(el => {
    el.style.display = 'none';
  });
}

// 显示AI相关显示
function showAIStats() {
  document.querySelectorAll('.ai-stats').forEach(el => {
    el.style.display = 'flex';
  });
}

// 初始化移动端控制
function initMobileControls() {
  // 方向按钮控制
  document.getElementById('upBtn').addEventListener('touchstart', function(e) {
    e.preventDefault();
    if (game.direction !== 'down') {
      game.direction = 'up';
    }
  });
  
  document.getElementById('downBtn').addEventListener('touchstart', function(e) {
    e.preventDefault();
    if (game.direction !== 'up') {
      game.direction = 'down';
    }
  });
  
  document.getElementById('leftBtn').addEventListener('touchstart', function(e) {
    e.preventDefault();
    if (game.direction !== 'right') {
      game.direction = 'left';
    }
  });
  
  document.getElementById('rightBtn').addEventListener('touchstart', function(e) {
    e.preventDefault();
    if (game.direction !== 'left') {
      game.direction = 'right';
    }
  });
  
  // 为了更好的响应体验，同时绑定点击事件
  document.getElementById('upBtn').addEventListener('click', function() {
    if (game.direction !== 'down') {
      game.direction = 'up';
    }
  });
  
  document.getElementById('downBtn').addEventListener('click', function() {
    if (game.direction !== 'up') {
      game.direction = 'down';
    }
  });
  
  document.getElementById('leftBtn').addEventListener('click', function() {
    if (game.direction !== 'right') {
      game.direction = 'left';
    }
  });
  
  document.getElementById('rightBtn').addEventListener('click', function() {
    if (game.direction !== 'left') {
      game.direction = 'right';
    }
  });
  
  // 防止向下滚动
  document.querySelectorAll('.direction-btn').forEach(btn => {
    btn.addEventListener('touchmove', function(e) {
      e.preventDefault();
    });
  });
}

// 初始化游戏说明弹窗
function initInstructionsModal() {
  const showBtn = document.getElementById('showInstructions');
  const modal = document.getElementById('instructionsModal');
  const closeBtn = document.getElementById('closeInstructions');
  
  if (!showBtn || !modal || !closeBtn) return;
  
  // 显示游戏说明弹窗
  showBtn.addEventListener('click', function() {
    modal.style.display = 'flex';
    
    // 如果游戏正在运行，暂停游戏
    if (game.isRunning && !game.isPaused) {
      game.isPaused = true;
    }
  });
  
  // 关闭游戏说明弹窗
  closeBtn.addEventListener('click', function() {
    modal.style.display = 'none';
  });
  
  // 点击弹窗外部区域关闭弹窗
  modal.addEventListener('click', function(e) {
    if (e.target === modal) {
      modal.style.display = 'none';
    }
  });
}

// 开始游戏
function startGame() {
  if (!game.isRunning) {
    game.isRunning = true;
    game.startTime = Date.now();
    document.getElementById('startBtn').style.display = 'none';
    document.getElementById('pauseBtn').style.display = 'block';
    gameLoop();
  }
}

// 暂停/继续游戏
function togglePause() {
  if (!game.isRunning) return;
  
  game.isPaused = !game.isPaused;
  const pauseBtn = document.getElementById('pauseBtn');
  
  if (game.isPaused) {
    pauseBtn.textContent = '继续';
  } else {
    pauseBtn.textContent = '暂停';
    gameLoop(); // 继续游戏循环
  }
}

// 重新开始游戏
function restartGame() {
  initGame();
  startGame();
}

// 切换障碍物模式
function toggleObstacleMode() {
  game.obstacleMode = !game.obstacleMode;
  
  const obstacleBtn = document.getElementById('obstacleModeBtn');
  obstacleBtn.textContent = game.obstacleMode ? '关闭障碍' : '障碍模式';
  
  if (game.obstacleMode) {
    generateObstacles();
  } else {
    game.obstacles = [];
  }
  
  // 重新绘制游戏
  draw();
}

// 切换AI模式
function toggleAIMode() {
  game.aiMode = !game.aiMode;
  
  const aiBtn = document.getElementById('aiModeBtn');
  aiBtn.textContent = game.aiMode ? '关闭AI' : 'AI对战';
  
  if (game.aiMode) {
    showAIStats();
    
    // 如果游戏尚未开始，自动开始游戏
    if (!game.isRunning) {
      startGame();
    }
  } else {
    hideAIStats();
  }
  
  // 重新绘制游戏
  draw();
}

// 生成障碍物
function generateObstacles() {
  if (!game.obstacleMode) return;
  
  // 清空现有障碍物
  game.obstacles = [];
  
  // 根据难度设置障碍物数量
  const diffSettings = DIFFICULTY_SETTINGS[game.difficulty];
  const obstacleCount = Math.floor(Math.random() * 
    (diffSettings.obstacleCount.max - diffSettings.obstacleCount.min + 1)) + 
    diffSettings.obstacleCount.min;
  
  // 计算网格数量
  const gridWidth = Math.floor(canvas.width / game.gridSize);
  const gridHeight = Math.floor(canvas.height / game.gridSize);
  
  // 生成障碍物
  for (let i = 0; i < obstacleCount; i++) {
    let obstacle;
    let isValid = false;
    
    // 尝试生成不与蛇、食物和其他障碍物重叠的障碍物位置
    while (!isValid) {
      obstacle = {
        x: Math.floor(Math.random() * gridWidth),
        y: Math.floor(Math.random() * gridHeight)
      };
      
      isValid = true;
      
      // 检查是否与蛇重叠
      for (const segment of game.snake) {
        if (segment.x === obstacle.x && segment.y === obstacle.y) {
          isValid = false;
          break;
        }
      }
      
      // 检查是否与AI蛇重叠
      if (isValid && game.aiMode) {
        for (const segment of game.aiSnake) {
          if (segment.x === obstacle.x && segment.y === obstacle.y) {
            isValid = false;
            break;
          }
        }
      }
      
      // 检查是否与食物重叠
      if (isValid && game.food && 
          obstacle.x === game.food.x && obstacle.y === game.food.y) {
        isValid = false;
      }
      
      // 检查是否与其他障碍物重叠
      if (isValid) {
        for (const existing of game.obstacles) {
          if (existing.x === obstacle.x && existing.y === obstacle.y) {
            isValid = false;
            break;
          }
        }
      }
    }
    
    game.obstacles.push(obstacle);
  }
}

// 生成食物
function generateFood() {
  // 计算网格数量
  const gridWidth = Math.floor(canvas.width / game.gridSize);
  const gridHeight = Math.floor(canvas.height / game.gridSize);
  
  let foodX, foodY, isValid;
  
  // 尝试生成不与蛇、AI蛇和障碍物重叠的食物位置
  do {
    foodX = Math.floor(Math.random() * gridWidth);
    foodY = Math.floor(Math.random() * gridHeight);
    isValid = true;
    
    // 检查是否与蛇重叠
    for (const segment of game.snake) {
      if (segment.x === foodX && segment.y === foodY) {
        isValid = false;
        break;
      }
    }
    
    // 检查是否与AI蛇重叠
    if (isValid && game.aiMode) {
      for (const segment of game.aiSnake) {
        if (segment.x === foodX && segment.y === foodY) {
          isValid = false;
          break;
        }
      }
    }
    
    // 检查是否与障碍物重叠
    if (isValid && game.obstacleMode) {
      for (const obstacle of game.obstacles) {
        if (obstacle.x === foodX && obstacle.y === foodY) {
          isValid = false;
          break;
        }
      }
    }
  } while (!isValid);
  
  // 选择食物类型
  const foodType = selectFoodType();
  
  // 创建新食物
  game.food = {
    x: foodX,
    y: foodY,
    type: foodType
  };
}

// 选择食物类型
function selectFoodType() {
  const diffSettings = DIFFICULTY_SETTINGS[game.difficulty];
  const foodProb = diffSettings.foodProbability;
  
  const random = Math.random();
  let cumProb = 0;
  
  for (const [type, prob] of Object.entries(foodProb)) {
    cumProb += prob;
    if (random <= cumProb) {
      return type;
    }
  }
  
  return 'normal'; // 默认返回普通食物
}

// 添加特效显示
function addEffectElement(name, duration, color) {
  const effectsContainer = document.getElementById('effects');
  if (!effectsContainer) return;
  
  const effectEl = document.createElement('div');
  effectEl.className = 'effect';
  effectEl.textContent = `${name}: ${duration}s`;
  effectEl.style.color = color;
  effectEl.style.borderLeft = `3px solid ${color}`;
  
  effectsContainer.appendChild(effectEl);
}

// 更新显示
function updateDisplay() {
  // 更新分数
  document.getElementById('score').textContent = game.score;
  document.getElementById('highScore').textContent = game.highScore;
  
  // 更新长度
  document.getElementById('length').textContent = game.snake.length;
  
  // 更新时间
  const minutes = Math.floor(game.gameTime / 60);
  const seconds = Math.floor(game.gameTime % 60);
  document.getElementById('time').textContent = 
    `${minutes}:${seconds.toString().padStart(2, '0')}`;
  
  // 更新AI分数显示
  if (game.aiMode) {
    document.getElementById('aiScore').textContent = game.aiScore;
    document.getElementById('aiLength').textContent = game.aiSnake.length;
  }
  
  // 更新速度显示
  document.getElementById('speedValue').textContent = 
    Math.floor((300 - game.speed) / 25);
}

// 更新特殊效果显示
function updateEffectsDisplay() {
  const effectsContainer = document.getElementById('effects');
  if (!effectsContainer) return;
  
  effectsContainer.innerHTML = '';
  
  const now = Date.now();
  
  if (game.effects.speedBoost && now < game.effects.speedBoostEndTime) {
    const timeLeft = Math.ceil((game.effects.speedBoostEndTime - now) / 1000);
    addEffectElement('速度', timeLeft, '#FFC107');
  } else {
    game.effects.speedBoost = false;
  }
  
  if (game.effects.doubleScore && now < game.effects.doubleScoreEndTime) {
    const timeLeft = Math.ceil((game.effects.doubleScoreEndTime - now) / 1000);
    addEffectElement('双倍分数', timeLeft, '#9C27B0');
  } else {
    game.effects.doubleScore = false;
  }
  
  if (game.effects.shield && now < game.effects.shieldEndTime) {
    const timeLeft = Math.ceil((game.effects.shieldEndTime - now) / 1000);
    addEffectElement('护盾', timeLeft, '#2196F3');
  } else {
    game.effects.shield = false;
  }
}

// 检查特殊效果
function checkEffects() {
  const now = Date.now();
  
  // 检查效果是否过期
  if (game.effects.speedBoost && now >= game.effects.speedBoostEndTime) {
    game.effects.speedBoost = false;
  }
  
  if (game.effects.doubleScore && now >= game.effects.doubleScoreEndTime) {
    game.effects.doubleScore = false;
  }
  
  if (game.effects.shield && now >= game.effects.shieldEndTime) {
    game.effects.shield = false;
  }
  
  // 更新效果显示
  updateEffectsDisplay();
}

// 游戏循环
function gameLoop() {
  if (!game.isRunning) return;
  if (game.isPaused) {
    requestAnimationFrame(gameLoop);
    return;
  }
  
  // 更新游戏时间
  const currentTime = Date.now();
  game.gameTime = (currentTime - game.startTime) / 1000;
  
  // 检查特殊效果状态
  checkEffects();
  
  // 移动蛇
  moveSnake();
  
  // 如果游戏结束，不执行后续代码
  if (!game.isRunning) return;
  
  // 移动AI蛇
  if (game.aiMode) {
    moveAISnake();
  }
  
  // 更新显示
  updateDisplay();
  
  // 绘制游戏画面
  draw();
  
  // 设置下一次更新的时间
  const speed = game.effects.speedBoost ? game.speed * 0.7 : game.speed;
  setTimeout(() => {
    requestAnimationFrame(gameLoop);
  }, speed);
}

// 移动蛇
function moveSnake() {
  // 获取蛇头
  const head = {...game.snake[0]};
  
  // 根据方向移动
  switch (game.direction) {
    case 'up': head.y--; break;
    case 'down': head.y++; break;
    case 'left': head.x--; break;
    case 'right': head.x++; break;
  }
  
  // 检查碰撞
  if (checkCollision(head)) {
    gameOver();
    return;
  }
  
  // 将新头部添加到蛇身
  game.snake.unshift(head);
  
  // 检查是否吃到食物
  if (game.food && head.x === game.food.x && head.y === game.food.y) {
    // 应用食物效果
    applyFoodEffect(game.food.type);
    
    // 更新分数
    const baseScore = FOOD_TYPES[game.food.type].score;
    const diffMultiplier = DIFFICULTY_SETTINGS[game.difficulty].scoreMultiplier;
    const doubleMultiplier = game.effects.doubleScore ? 2 : 1;
    game.score += Math.floor(baseScore * diffMultiplier * doubleMultiplier);
    
    // 更新最高分
    if (game.score > game.highScore) {
      game.highScore = game.score;
      localStorage.setItem('snakeHighScore', game.highScore);
    }
    
    // 生成新食物
    generateFood();
  } else {
    // 未吃到食物，移除尾部
    game.snake.pop();
  }
}

// 移动AI蛇
function moveAISnake() {
  if (!game.aiMode) return;
  
  // 获取AI蛇头和食物位置
  const head = {...game.aiSnake[0]};
  const food = game.food;
  
  // 简单的AI决策：尝试移动到食物位置
  let newDirection = game.aiDirection;
  
  // 水平方向优先
  if (head.x < food.x && game.aiDirection !== 'left') {
    newDirection = 'right';
  } else if (head.x > food.x && game.aiDirection !== 'right') {
    newDirection = 'left';
  } else if (head.y < food.y && game.aiDirection !== 'up') {
    newDirection = 'down';
  } else if (head.y > food.y && game.aiDirection !== 'down') {
    newDirection = 'up';
  }
  
  // 检查新方向是否导致碰撞，如果是则尝试其他方向
  const directions = ['up', 'right', 'down', 'left'];
  const opposites = {
    'up': 'down',
    'down': 'up',
    'left': 'right',
    'right': 'left'
  };
  
  let newHead = {...head};
  switch (newDirection) {
    case 'up': newHead.y--; break;
    case 'down': newHead.y++; break;
    case 'left': newHead.x--; break;
    case 'right': newHead.x++; break;
  }
  
  // 如果新方向会导致碰撞，尝试其他方向
  if (checkAICollision(newHead)) {
    for (const dir of directions) {
      // 跳过与当前方向相反的方向
      if (dir === opposites[game.aiDirection]) continue;
      
      // 创建新的头部位置
      newHead = {...head};
      switch (dir) {
        case 'up': newHead.y--; break;
        case 'down': newHead.y++; break;
        case 'left': newHead.x--; break;
        case 'right': newHead.x++; break;
      }
      
      // 检查该方向是否安全
      if (!checkAICollision(newHead)) {
        newDirection = dir;
        break;
      }
    }
  }
  
  // 更新AI蛇方向
  game.aiDirection = newDirection;
  
  // 根据新方向移动
  switch (newDirection) {
    case 'up': head.y--; break;
    case 'down': head.y++; break;
    case 'left': head.x--; break;
    case 'right': head.x++; break;
  }
  
  // 检查碰撞
  if (checkAICollision(head)) {
    // AI蛇碰撞，玩家获胜
    game.aiMode = false;
    hideAIStats();
    document.getElementById('aiModeBtn').textContent = 'AI对战';
    return;
  }
  
  // 将新头部添加到AI蛇身
  game.aiSnake.unshift(head);
  
  // 检查是否吃到食物
  if (game.food && head.x === game.food.x && head.y === game.food.y) {
    // 更新AI分数
    game.aiScore += FOOD_TYPES[game.food.type].score;
    
    // 生成新食物
    generateFood();
  } else {
    // 未吃到食物，移除尾部
    game.aiSnake.pop();
  }
}

// 检查蛇的碰撞
function checkCollision(head) {
  // 如果有护盾，不检查碰撞
  if (game.effects.shield) return false;
  
  // 计算网格数量
  const gridWidth = Math.floor(canvas.width / game.gridSize);
  const gridHeight = Math.floor(canvas.height / game.gridSize);
  
  // 检查边界碰撞
  if (head.x < 0 || head.x >= gridWidth || head.y < 0 || head.y >= gridHeight) {
    return true;
  }
  
  // 检查自身碰撞
  for (let i = 1; i < game.snake.length; i++) {
    if (head.x === game.snake[i].x && head.y === game.snake[i].y) {
      return true;
    }
  }
  
  // 检查障碍物碰撞
  if (game.obstacleMode) {
    for (const obstacle of game.obstacles) {
      if (head.x === obstacle.x && head.y === obstacle.y) {
        return true;
      }
    }
  }
  
  // 检查与AI蛇的碰撞
  if (game.aiMode) {
    for (const segment of game.aiSnake) {
      if (head.x === segment.x && head.y === segment.y) {
        return true;
      }
    }
  }
  
  return false;
}

// 检查AI蛇的碰撞
function checkAICollision(head) {
  // 计算网格数量
  const gridWidth = Math.floor(canvas.width / game.gridSize);
  const gridHeight = Math.floor(canvas.height / game.gridSize);
  
  // 检查边界碰撞
  if (head.x < 0 || head.x >= gridWidth || head.y < 0 || head.y >= gridHeight) {
    return true;
  }
  
  // 检查自身碰撞
  for (let i = 1; i < game.aiSnake.length; i++) {
    if (head.x === game.aiSnake[i].x && head.y === game.aiSnake[i].y) {
      return true;
    }
  }
  
  // 检查障碍物碰撞
  if (game.obstacleMode) {
    for (const obstacle of game.obstacles) {
      if (head.x === obstacle.x && head.y === obstacle.y) {
        return true;
      }
    }
  }
  
  // 检查与玩家蛇的碰撞
  for (const segment of game.snake) {
    if (head.x === segment.x && head.y === segment.y) {
      return true;
    }
  }
  
  return false;
}

// 应用食物效果
function applyFoodEffect(foodType) {
  if (foodType === 'normal') return;
  
  const now = Date.now();
  const foodConfig = FOOD_TYPES[foodType];
  
  switch (foodType) {
    case 'speedBoost':
      game.effects.speedBoost = true;
      game.effects.speedBoostEndTime = now + foodConfig.duration;
      break;
      
    case 'doubleScore':
      game.effects.doubleScore = true;
      game.effects.doubleScoreEndTime = now + foodConfig.duration;
      break;
      
    case 'shield':
      game.effects.shield = true;
      game.effects.shieldEndTime = now + foodConfig.duration;
      break;
  }
  
  // 更新效果显示
  updateEffectsDisplay();
}

// 绘制游戏
function draw() {
  // 清空画布
  ctx.fillStyle = '#121212';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  // 绘制网格
  drawGrid();
  
  // 绘制障碍物
  if (game.obstacleMode) {
    drawObstacles();
  }
  
  // 绘制食物
  if (game.food) {
    drawFood();
  }
  
  // 如果是AI模式，绘制AI蛇
  if (game.aiMode) {
    drawSnake(game.aiSnake, false);
  }
  
  // 绘制玩家蛇
  drawSnake(game.snake, true);
}

// 绘制网格
function drawGrid() {
  ctx.strokeStyle = 'rgba(255, 255, 255, 0.05)';
  ctx.lineWidth = 1;
  
  // 绘制垂直网格线
  for (let x = 0; x <= canvas.width; x += game.gridSize) {
    ctx.beginPath();
    ctx.moveTo(x, 0);
    ctx.lineTo(x, canvas.height);
    ctx.stroke();
  }
  
  // 绘制水平网格线
  for (let y = 0; y <= canvas.height; y += game.gridSize) {
    ctx.beginPath();
    ctx.moveTo(0, y);
    ctx.lineTo(canvas.width, y);
    ctx.stroke();
  }
}

// 绘制障碍物
function drawObstacles() {
  ctx.fillStyle = '#795548';
  
  for (const obstacle of game.obstacles) {
    ctx.fillRect(
      obstacle.x * game.gridSize + 1,
      obstacle.y * game.gridSize + 1,
      game.gridSize - 2,
      game.gridSize - 2
    );
  }
}

// 绘制食物
function drawFood() {
  const foodType = game.food.type;
  const foodColor = FOOD_TYPES[foodType].color;
  
  // 食物位置
  const x = game.food.x * game.gridSize + game.gridSize / 2;
  const y = game.food.y * game.gridSize + game.gridSize / 2;
  const radius = game.gridSize / 2 - 2;
  
  // 绘制食物底色
  ctx.fillStyle = foodColor;
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, Math.PI * 2);
  ctx.fill();
  
  // 根据食物类型添加图标
  ctx.fillStyle = '#fff';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  
  switch (foodType) {
    case 'speedBoost':
      // 绘制闪电图标
      ctx.strokeStyle = '#fff';
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.moveTo(x - radius/3, y - radius/3);
      ctx.lineTo(x + radius/3, y - radius/3);
      ctx.lineTo(x, y + radius/3);
      ctx.stroke();
      break;
      
    case 'doubleScore':
      // 绘制2X图标
      ctx.font = `bold ${radius}px Arial`;
      ctx.fillText('2×', x, y);
      break;
      
    case 'shield':
      // 绘制盾牌图标
      ctx.strokeStyle = '#fff';
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.arc(x, y, radius * 0.6, 0, Math.PI * 2);
      ctx.stroke();
      break;
  }
}

// 绘制蛇
function drawSnake(snake, isPlayer) {
  // 根据是玩家还是AI选择不同的颜色
  const headColor = isPlayer ? '#4CAF50' : '#F44336';
  const bodyColor = isPlayer ? '#388E3C' : '#D32F2F';
  
  // 如果玩家有护盾效果
  const hasShield = isPlayer && game.effects.shield;
  
  // 绘制蛇身
  for (let i = snake.length - 1; i >= 0; i--) {
    const segment = snake[i];
    
    // 蛇头与蛇身不同颜色
    ctx.fillStyle = i === 0 ? headColor : bodyColor;
    
    // 如果有护盾效果，添加蓝色光晕
    if (hasShield) {
      ctx.shadowColor = '#2196F3';
      ctx.shadowBlur = 10;
    }
    
    // 绘制圆角矩形
    const x = segment.x * game.gridSize;
    const y = segment.y * game.gridSize;
    const size = game.gridSize - 2;
    const radius = size / 4;
    
    ctx.beginPath();
    ctx.moveTo(x + radius, y);
    ctx.lineTo(x + size - radius, y);
    ctx.quadraticCurveTo(x + size, y, x + size, y + radius);
    ctx.lineTo(x + size, y + size - radius);
    ctx.quadraticCurveTo(x + size, y + size, x + size - radius, y + size);
    ctx.lineTo(x + radius, y + size);
    ctx.quadraticCurveTo(x, y + size, x, y + size - radius);
    ctx.lineTo(x, y + radius);
    ctx.quadraticCurveTo(x, y, x + radius, y);
    ctx.closePath();
    ctx.fill();
    
    // 绘制蛇头眼睛（只对蛇头绘制）
    if (i === 0) {
      ctx.fillStyle = '#fff';
      
      // 根据蛇的方向确定眼睛位置
      const direction = isPlayer ? game.direction : game.aiDirection;
      let eyeX1, eyeY1, eyeX2, eyeY2;
      const eyeSize = game.gridSize / 6;
      const eyeOffset = game.gridSize / 4;
      
      switch(direction) {
        case 'up':
          eyeX1 = x + eyeOffset;
          eyeY1 = y + eyeOffset;
          eyeX2 = x + size - eyeOffset;
          eyeY2 = y + eyeOffset;
          break;
        case 'down':
          eyeX1 = x + eyeOffset;
          eyeY1 = y + size - eyeOffset;
          eyeX2 = x + size - eyeOffset;
          eyeY2 = y + size - eyeOffset;
          break;
        case 'left':
          eyeX1 = x + eyeOffset;
          eyeY1 = y + eyeOffset;
          eyeX2 = x + eyeOffset;
          eyeY2 = y + size - eyeOffset;
          break;
        case 'right':
          eyeX1 = x + size - eyeOffset;
          eyeY1 = y + eyeOffset;
          eyeX2 = x + size - eyeOffset;
          eyeY2 = y + size - eyeOffset;
          break;
      }
      
      // 绘制眼睛
      ctx.beginPath();
      ctx.arc(eyeX1, eyeY1, eyeSize, 0, Math.PI * 2);
      ctx.fill();
      
      ctx.beginPath();
      ctx.arc(eyeX2, eyeY2, eyeSize, 0, Math.PI * 2);
      ctx.fill();
      
      // 绘制瞳孔
      ctx.fillStyle = '#000';
      
      ctx.beginPath();
      ctx.arc(eyeX1, eyeY1, eyeSize / 2, 0, Math.PI * 2);
      ctx.fill();
      
      ctx.beginPath();
      ctx.arc(eyeX2, eyeY2, eyeSize / 2, 0, Math.PI * 2);
      ctx.fill();
    }
    
    // 重置阴影
    if (hasShield) {
      ctx.shadowColor = 'transparent';
      ctx.shadowBlur = 0;
    }
  }
}

// 游戏结束
function gameOver() {
  game.isRunning = false;
  
  // 更新最高分
  if (game.score > game.highScore) {
    game.highScore = game.score;
    // 储存最高分
    localStorage.setItem('snakeHighScore', game.highScore);
  }
  
  // 更新结算界面内容
  document.getElementById('finalScore').textContent = game.score;
  document.getElementById('finalLength').textContent = game.snake.length;
  document.getElementById('finalHighScore').textContent = game.highScore;
  document.getElementById('finalTime').textContent = `${Math.floor(game.gameTime)}秒`;
  
  // 根据游戏模式设置界面样式
  const modal = document.getElementById('gameOverModal');
  
  // 设置模式标签
  const modeBadge = document.getElementById('modeBadge');
  
  if (game.aiMode) {
    modeBadge.textContent = 'AI对战模式';
    modeBadge.style.background = '#F44336';
    
    // 显示AI数据
    document.getElementById('aiStatsContainer').style.display = 'flex';
    document.getElementById('aiLengthContainer').style.display = 'flex';
    document.getElementById('finalAiScore').textContent = game.aiScore;
    document.getElementById('finalAiLength').textContent = game.aiSnake.length;
    
    // 确定胜负
    const result = game.score > game.aiScore ? '你赢了！' : (game.score < game.aiScore ? 'AI赢了！' : '平局！');
    document.querySelector('.modal-title').textContent = result;
  } else if (game.obstacleMode) {
    modeBadge.textContent = '障碍模式';
    modeBadge.style.background = '#795548';
    
    // 隐藏AI数据
    document.getElementById('aiStatsContainer').style.display = 'none';
    document.getElementById('aiLengthContainer').style.display = 'none';
    
    document.querySelector('.modal-title').textContent = '游戏结束';
  } else {
    modeBadge.textContent = '标准模式';
    modeBadge.style.background = '#4CAF50';
    
    // 隐藏AI数据
    document.getElementById('aiStatsContainer').style.display = 'none';
    document.getElementById('aiLengthContainer').style.display = 'none';
    
    document.querySelector('.modal-title').textContent = '游戏结束';
  }
  
  // 显示结算界面
  modal.style.display = 'flex';
  
  // 为结算界面按钮添加事件监听
  document.getElementById('modalRestartBtn').addEventListener('click', function() {
    modal.style.display = 'none';
    initGame();
    startGame();
  });
  
  document.getElementById('modalMenuBtn').addEventListener('click', function() {
    modal.style.display = 'none';
    initGame();
  });
  
  document.getElementById('modalShareBtn').addEventListener('click', shareScore);
}

// 分享分数
function shareScore() {
  let shareText = `我在贪吃蛇游戏中获得了 ${game.score} 分，长度达到了 ${game.snake.length}！`;
  
  if (game.obstacleMode) {
    shareText += '（障碍模式）';
  }
  
  if (game.aiMode) {
    const result = game.score > game.aiScore ? '战胜了AI！' : (game.score < game.aiScore ? '被AI击败了。' : '与AI打成了平手！');
    shareText += `在AI对战中${result}`;
  }
  
  // 尝试使用分享API
  if (navigator.share) {
    navigator.share({
      title: '贪吃蛇游戏成绩',
      text: shareText
    }).catch(err => {
      console.error('分享失败:', err);
      copyToClipboard(shareText);
    });
  } else {
    // 复制到剪贴板
    copyToClipboard(shareText);
  }
}

// 复制文本到剪贴板
function copyToClipboard(text) {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text)
      .then(() => alert('分享文本已复制到剪贴板！'))
      .catch(err => {
        console.error('复制失败:', err);
        alert(text);
      });
  } else {
    alert(text);
  }
}

// 按键控制（保留键盘控制支持）
document.addEventListener('keydown', function(e) {
  if (!game.isRunning) return;
  
  // 阻止方向键的默认行为（页面滚动）
  if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', ' '].includes(e.key)) {
    e.preventDefault();
  }
  
  // 暂停控制
  if (e.key === ' ') {
    togglePause();
    return;
  }
  
  if (game.isPaused) return;
  
  // 方向控制
  switch(e.key) {
    case 'ArrowUp':
      if (game.direction !== 'down') game.direction = 'up';
      break;
    case 'ArrowDown':
      if (game.direction !== 'up') game.direction = 'down';
      break;
    case 'ArrowLeft':
      if (game.direction !== 'right') game.direction = 'left';
      break;
    case 'ArrowRight':
      if (game.direction !== 'left') game.direction = 'right';
      break;
  }
});